﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sunboxsoft.WinForm
{
    public class UIContext
    {
        public ModuleRuntimeContext ModuleRuntimeContext { get; private set; }
        public IViewManager ViewManager { get; private set; }
        public INavigatorManager NavigatorManager { get; private set; }
        public ViewContext ViewContext { get; private set; }
        public Config Config { get; set; }

        private static UIContext s_instance;
        public static UIContext Current
        {
            get
            {
                if (s_instance == null)
                {
                    s_instance = new UIContext();
                }
                return s_instance;
            }
        }

        private UIContext()
        {
            ModuleRuntimeContext = new ModuleRuntimeContext();
            ViewContext = new ViewContext();
        }

        public void RegisterManager(IViewManager viewManager, INavigatorManager navigatorManager)
        {
            if (ViewManager == null)
            {
                ViewManager = viewManager;
            }

            if (NavigatorManager == null)
            {
                NavigatorManager = navigatorManager;
            }
        }

        /// <summary>
        /// 异步执行
        /// </summary>
        /// <param name="action"></param>
        public void InvokeAsync(Action action)
        {
            action.BeginInvoke(InvokeAsyncCallback, null);
        }

        private void InvokeAsyncCallback(IAsyncResult asyncResult)
        {
        }

        /// <summary>
        /// 激活功能项
        /// </summary>
        /// <param name="name"></param>
        public void ActiveActionNode(string name)
        {
            ActionNode action = null;

            Queue<ActionNode> stack = new Queue<ActionNode>();
            for (int index = 0; index < ModuleRuntimeContext.Roots.Count; index++)
            {
                stack.Enqueue(ModuleRuntimeContext.Roots[index]);
            }

            while (stack.Count > 0)
            {
                ActionNode node = stack.Dequeue();

                if (string.Equals(node.Name, name))
                {
                    action = node;
                    break;
                }

                if (node.Children != null)
                {
                    for (int index = 0; index < node.Children.Count; index++)
                    {
                        stack.Enqueue(node.Children[index]);
                    }
                }
            }

            if (action == null)
            {
                return;
            }
            NavigatorManager.ActiveAction(action);
        }

        public void ActiveActionNode(ActionNode node)
        {
            NavigatorManager.ActiveAction(node);
        }
    }
}
